package com.zxz.mq.task;

import com.alibaba.fastjson.JSON;
import com.zxz.mq.dto.TransMessageDto;
import com.zxz.mq.service.IMessageSendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@EnableScheduling
@Configuration
@Component
@Slf4j
public class MessageSendTask {
    @Autowired
    private IMessageSendService messageSendService;

    @Autowired
    @Qualifier("myRabbitAdmin")
    private RabbitAdmin myRabbitAdmin;

    @Value("${my.mq.resend.times}")
    private int times;

    @Scheduled(fixedRateString = "0 0/30 * * * ?")
    public void messageSend(){
        List<TransMessageDto> messageDtos = messageSendService.messageSendReadyList();
        log.info("messageSend():messageDtos size:{}", messageDtos.size());
        for (TransMessageDto transMessageDto : messageDtos){
            log.info("messageSend():transMessageDto :{}", transMessageDto);
            if(transMessageDto.getSequence() > times){
                log.error("ressage resend too many times! transMessageDto:{}",transMessageDto);
                messageSendService.messageDead(transMessageDto.getId());
            }

            myRabbitAdmin.getRabbitTemplate().convertAndSend(transMessageDto.getExchange(), transMessageDto.getRoutingKey(), JSON.toJSONString(transMessageDto), new CorrelationData(transMessageDto.getId()));
            messageSendService.messageResend(transMessageDto.getId());
        }
    }
}
